package org.tlipoca.smsteamuserstore.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.C;
import org.genntii.smcommon.constant.SteamApiURLConstant;
import org.genntii.smcommon.constant.SteamConstant;
import org.genntii.smcommon.result.PageResult;
import org.genntii.smcommon.utils.HttpClientUtil;
import org.genntii.smdomain.entity.SteamAppDetail;
import org.genntii.smdomain.entity.SteamUserStore;
import org.genntii.smdomain.vo.SteamUserStoreMessageVO;
import org.genntii.smdomain.vo.SteamUserStoreVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.tlipoca.smsteamuserstore.mapper.SteamUserStoreMapper;
import org.tlipoca.smsteamuserstore.service.SteamUserStoreService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class SteamUserStoreServiceImpl extends ServiceImpl<SteamUserStoreMapper, SteamUserStore> implements SteamUserStoreService {

    @Autowired
    private SteamUserStoreMapper steamUserStoreMapper;

    @Resource
    private MongoTemplate mongoTemplate;

    @Override
    public void updateSteamUserStoreBySteamIdService(Long steamid) {
        log.info("更新库存信息");
        List<SteamUserStore> games = getSteamUserStoreFromSteamApi(steamid);
        log.info("获取库存信息成功");
        // 遍历获取的库存信息
        for (SteamUserStore game : games) {
            // 判断是否为新增游戏 检查Mysql是否存在与Steamid、appid相等的数据
            QueryWrapper<SteamUserStore> query = new QueryWrapper<SteamUserStore>().eq("appid", game.getAppid()).eq("steamid", game.getSteamid());
            if(steamUserStoreMapper.exists(query)) {
                // 此前已存在 更新数据
                steamUserStoreMapper.update(game, query);
            }

            // 新增库存 插入数据
            steamUserStoreMapper.insert(game);
        }
    }

    @Override
    public ArrayList<SteamUserStore> getSteamUserStoreBySteamIdService(Long steamid) {

        // 判断数据库中是否存在该steamid的库存信息
        if(!steamUserStoreMapper.exists(new QueryWrapper<SteamUserStore>().eq("steamid", steamid))) {
            log.info("Mysql不存在用户库存信息 尝试请求SteamApi");
            List<SteamUserStore> games = getSteamUserStoreFromSteamApi(steamid);
            log.info("请求成功");
            // 新增数据库
            steamUserStoreMapper.insertSteamUserStoreBatch(games);
        }

        // 存在 返回数据
        return steamUserStoreMapper.selectSteamUserGameBySteamId(steamid);
    }

    private List<SteamUserStore> getSteamUserStoreFromSteamApi(Long steamid) {
        // 不存在 从SteamApi获取用户库存信息 更新数据库
        Map<String , Object> map = Map.of("key", SteamConstant.STEAM_KEY, "language", SteamConstant.STEAM_CHINESE_LANGUAGE, "steamid", steamid, "include_appinfo", true, "include_played_free_games", true, "include_free_sub", true, "skip_unvetted_apps", true, "include_extended_appinfo", true);
        JSONObject response = (JSONObject) JSON.parseObject(HttpClientUtil.doGetWithRetry(SteamApiURLConstant.GET_USER_STORE, map, 100)).get("response");
        System.out.println(response);
        List<SteamUserStore> games = JSON.parseArray(response.get("games").toString(), SteamUserStore.class);

        for (SteamUserStore game : games) {
            game.setDlc(false);
            game.setSteamid(steamid);
            game.setImgIconUrl("http://media.steampowered.com/steamcommunity/public/images/apps/" + game.getAppid() + "/" + game.getImgIconUrl() + ".jpg");
        }

        return games;
    }

    @Override
    public SteamUserStoreVO getPlayerPlayedMessage(String steamid) {
        Long steamidL = Long.valueOf(steamid);
        Integer gameCount = steamUserStoreMapper.getGameCount(steamidL);
        ArrayList<SteamUserStore> steamUserStores = steamUserStoreMapper.getSteamUserStoreList(steamidL);
        Integer play2week = 0;
        Integer playForever = 0;
        for (SteamUserStore steamUserStore:steamUserStores){
            if (steamUserStore.getPlaytime2weeks() != null) play2week += steamUserStore.getPlaytime2weeks();
            if (steamUserStore.getPlaytimeForever() != null) playForever += steamUserStore.getPlaytimeForever();
        }
        return new SteamUserStoreVO(play2week,playForever,gameCount);
    }

    @Override
    public PageResult<SteamUserStoreMessageVO> getSteamUserStoreDetail(Long steamid, Integer pageNum, Integer pageSize) {
//        ArrayList<SteamUserStore> steamUserStores = steamUserStoreMapper.getSteamUserStoreList(steamid, (pageNum-1)*pageSize, pageSize);
        ArrayList<SteamUserStore> steamUserStores = steamUserStoreMapper.getSteamUserStoreListToVO(steamid,(pageNum-1)*pageSize, pageSize);
        ArrayList<Integer> appidList = new ArrayList<>();
        Map<Integer, SteamUserStore> steamUserStoreMap = new HashMap<>();
        for (SteamUserStore steamUserStore:steamUserStores){
            steamUserStoreMap.put(steamUserStore.getAppid(),steamUserStore);
            appidList.add(steamUserStore.getAppid());
        }
        List<SteamAppDetail> steamAppDetailList = mongoTemplate.find(new Query(new Criteria("steam_appid").in(appidList)), SteamAppDetail.class);
        ArrayList<SteamUserStoreMessageVO> steamUserStoreMessageVOS = new ArrayList<>();
        for (SteamAppDetail steamAppDetail:steamAppDetailList){
            SteamUserStoreMessageVO steamUserStoreMessageVO = new SteamUserStoreMessageVO();
            BeanUtils.copyProperties(steamUserStoreMap.get(steamAppDetail.getSteam_appid()),steamUserStoreMessageVO);
            steamUserStoreMessageVO.setCoverImage(steamAppDetail.getHeader_image());
            steamUserStoreMessageVOS.add(steamUserStoreMessageVO);
        }
        return PageResult.build(steamUserStoreMessageVOS,steamUserStoreMapper.getSteamUserStoreCount(steamid));
    }
}
